#!/usr/bin/python
# -*- coding: utf-8 -*-
# This script fetches douban music favoriate list.

from urlparse import urlparse, urljoin
import urllib, sgmllib
from HTMLParser import HTMLParser
import re, sys, os
import google_music
import ID3

class MyParser(HTMLParser):
  def __init__(self):
    HTMLParser.__init__(self)
    self.num = 0
    self.albums = []
    
  def parse(self, url):
    req = urllib.urlopen(url)
    self.state = 0
    self.raw_text = req.read()
    req.close()
    self.raw_text = re.sub("&amp;","and",self.raw_text)
    self.feed(self.raw_text)
    
  def handle_starttag(self, tag, attrs):
    #print "Encountered the beginning of a %s tag" % tag
    try:
      if self.state == 0:
        if  tag == "table" and dict(attrs)["class"] =="olts":
          self.state = 1
          self.row = 0
      elif self.state == 1:
        if  tag == "tr":
          self.row += 1
          self.state = 2
      elif self.state == 2:
        if  tag == "td":
          self.state = 3
      elif self.state == 3:
        if tag == "a":
          self.state = 4
          href = [v for k,v in attrs if k=='href']
          self.album_url=href[0]
          #self.artist=get_artist(href[0])
        else:
          self.state = 1
      elif self.state == 4:
        self.state = 1
    except KeyError:
      pass

  def handle_endtag(self, tag):
    #print "Encountered the end of a %s tag" % tag
    if self.state >= 1 and tag == "table":
      self.state = 0

  def handle_data(self, data):
    if self.state == 3:
      if self.row > 1:
        #print "%d title"%(self.num), data[:-2],
        self.num += 1
        self.title = "".join(data[:-3].split("amp;"))
    elif self.state == 4:
      if data.strip():
        data = "".join(data.strip().split("amp;"))
        self.albums.append([self.title, data, self.album_url])

# @return artist
def get_artist(album_url):
  print ">>> Fetching Artist from album URL:", album_url
  expression='<span><span class="pl">表演者</span>: <a href=".*">(.*)</a></span>'
  usock=urllib.urlopen(album_url)
  html_content = usock.read()
  _artist = re.findall(expression, html_content)
  usock.close()
  # sometimes album_url maybe linked in a movie page
  # cannot fetch the artist in this situation, return None
  if _artist:
    return "".join(_artist[0].split("amp;"))
  else:
    return None
  
# @return [[title,album,album_url]]
def get_song_list(people_id):
  expression='共(.*)首'
  current_url_prefix = "http://www.douban.com/people/%d/songs"%(people_id)
  usock=urllib.urlopen(current_url_prefix)
  _songs_total = re.findall(expression, usock.read())
  if _songs_total:
    songs_total = int(_songs_total[0])
  else:
    songs_total = 20
  usock.close()
  myparser = MyParser()
  base = 0
  while base < songs_total: 
    current_url = "%s?start=%d"%(current_url_prefix, base)
    print ">>> Reading douban favoriate page:", current_url
    myparser.parse(current_url)
    base += 20
  print "<<< Done, all together %d songs"%(myparser.num)
  return myparser.albums
